package com.shitou.shitouproduct.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.shitou.shitoucommons.exception.RRException;
import com.shitou.shitoucommons.utils.AllSaltEnum;
import com.shitou.shitouproduct.config.RabbitMQConfit;
import com.shitou.shitouproduct.entity.SkuInfoEntity;
import com.shitou.shitouproduct.service.SkuInfoService;
import com.shitou.shitouproduct.service.SpuInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;


/**
 * class detail:
 *
 * @author 石头人
 */
@SuppressWarnings("all")
@Slf4j
@Transactional
@Component
public class ProductDecrementListener {

    @Autowired
    private SpuInfoService spuInfoService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    @Qualifier("RedisTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 将商品的售卖件数+1,,,
     *      也就是库存降低,,,奶奶的， 反的，但是懒得改了，嘎嘎嘎嘎
     * @param msg
     * @param channel
     * @param message
     */
    @RabbitListener(queues = {RabbitMQConfit.DECREMENT_SALECOUNT})
    public void decrementSaleCount(String msg, Channel channel, Message message){
        try {
            long[] spuIds = JSON.parseObject(msg, long[].class);
            if ( spuIds == null || spuIds.length <= 0){
                throw new RRException("传输过来的商品已经被售卖了");
            }
            for (long spuId : spuIds) {
                // 查出 所有的商品 售卖增加1
                SkuInfoEntity skuInfo = skuInfoService.getOne(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

                skuInfo.setSaleCount(1L);
                String productToken = String.valueOf(new Sha256Hash(String.valueOf(spuId), AllSaltEnum.SALT.getSalt()));
                redisTemplate.delete("saleCount:"+productToken);
                skuInfoService.updateById(skuInfo);
                // TODO 不知是否要删除该商品以及所有的信息，暂留


            }
        } catch (Exception e){
            e.printStackTrace();
            log.info("库存减少异常: {}", e.getMessage());
        }finally {
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                log.info("库存已经进行了修改，商品的已经售卖出去了，进行队列签收");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
